package com.five.novel.service.Impl;


import com.five.author.service.Impl.AuthorServiceImpl;
import com.five.basic.result.PageList;
import com.five.basic.service.impl.BaseServiceImpl;
import com.five.exception.BusinessException;
import com.five.novel.mapper.NovelMapper;
import com.five.novel.service.INovelService;
import com.five.pojo.Novel;
import com.five.vo.NovelRankVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NovelServiceImpl extends BaseServiceImpl<Novel> implements INovelService {

    @Autowired
    private NovelMapper novelMapper;

    @Autowired
    private NovelCategoryServiceImpl novelCategoryService;

    @Autowired
    private AuthorServiceImpl authorService;

    @Override
    public List<NovelRankVo> rankTop10Collect() {
        return novelMapper.selectTop10ByCollect();
    }


    /*
     * 查询小说数量
     **/
    @Override
    public Integer queryCount(Novel novel) {
        return novelMapper.queryCount(novel);
    }

    /*
     * 小说分类，作者id分页查询小说
     **/

    @Override
    public PageList<Novel> queryPage(Novel novel) {
        Integer total = novelMapper.queryCount(novel);
        if (total == null || total == 0) {
            return new PageList<>();
        }
        List<Novel> data = novelMapper.queryPage(novel);
        for (Novel novel1 : data){
            // 添加空值检查，避免空指针异常
            if (novel1.getCategoryId() != null) {
                novel1.setNovelCategory(novelCategoryService.queryById(novel1.getCategoryId()));
            }
            if (novel1.getAuthorId() != null) {
                novel1.setAuthor(authorService.selectById(novel1.getAuthorId()));
            }
        }
         return new PageList<>(total, data);
    }

    /*
     * 根据分类id查询小说
     **/
    @Override
    public List<NovelRankVo> listNovelByCategory(Long categoryId) {
        if (categoryId == null || categoryId <= 0) {
            throw new BusinessException("分类 ID 非法");
        }
        return novelMapper.selectByCategoryId(categoryId);
    }

}